package es.usal.proyecto.Controller;

import java.io.File;

import es.usal.proyecto.Model.Language;
import es.usal.proyecto.Model.LanguagesModel;
import android.content.Context;

public class LanguagesController {

	private Context context;
	private LanguagesModel lModel;
	
	public LanguagesController(Context context){
		this.context = context;
	}
	
	public boolean isLangAvailable(int langIndex){
	
		lModel = LanguagesModel.getInstance();
		Language lang = lModel.getLangByIndex(langIndex);
		
		if (lang != null){
			return lang.isAvailable();
		}
		return false; 
	}
	
	public void InitLanguageModel(String[] langs, String[] files, String[] langCodes){
		lModel = LanguagesModel.getInstance();
		String langPath = getLangPath() + "/tessdata";
		File langDir = new File(langPath);
		File[] listFiles = langDir.listFiles();
		boolean langFound = false;
		
		for (int i = 0; i < langs.length; i++) {
			
			if(listFiles != null){
				for (File file : listFiles) {
					if (file.getName().substring(0, 3).compareTo(langCodes[i]) == 0){
						langFound = true;
						break;
					}
				}
				if(langFound){
					lModel.addLanguage(langs[i], true, files[i]);	
				}else {
					lModel.addLanguage(langs[i], false, files[i]);
				}
				
			}else{
				lModel.addLanguage(langs[i], false, files[i]);
			}
				
			langFound = false;	
			
		}
	}
	
	public String getLangFileName(int langId){
		lModel = LanguagesModel.getInstance();
		Language lang = lModel.getLangByIndex(langId);
		return lang.getFileName();
	}
	
	public void modifyLang(int langIndex, boolean available, String fileName){
		lModel = LanguagesModel.getInstance();
		lModel.modifyLanguage(langIndex, available, fileName);
	}
	
	public String getLangOCRCode(int langId){
		String langCode;
		String langPack = getLangFileName(langId);
		langCode = langPack.substring(langPack.length()-10, langPack.length()-7);
		return langCode;
	}
	
	public String getLangPath(){
		String langPath;
		String appPath = context.getExternalFilesDir(null).getPath();
		langPath = appPath + "/tesseract-ocr/";
		return langPath;
	}
	
	public void installingLanguage(int langIndex){
		lModel = LanguagesModel.getInstance();
		lModel.installingLanguage(langIndex);
    }
	
	public boolean isInstallingLanguage (int langIndex){
		lModel = LanguagesModel.getInstance();
		return lModel.isInstallingLanguage(langIndex);
	}
}
